<?php

namespace App\Services\OpenGroup;

use App\Models\User;
use App\Models\Address;
use App\Models\ProductSku;
use App\Models\GoldRecord;
use App\Models\SeckillProduct;
use App\Models\ProductExpress;
use App\Models\ProductExtraExpress;
use Brick\Math\RoundingMode;
use App\Events\OrderCreatedEvent;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use Rainsens\Dinglog\Facades\Dinglog;
use Illuminate\Support\Facades\Redis;
use Carbon\Carbon;
use App\Jobs\CloseGroupJob;

class JoinGroup
{
	protected ?User $user = null;

	public function __construct(
		User $user,
		$group_id = 0
		)
	{
		$this->user = $user;
		$this->group_id = $group_id;
	}

	public function make()
	{
		DB::transaction(function () {

			$lastGroupCards = $this->user->groupCards()->canUsed()->first();

			$this->group = $this->user->groups()->create(['product_id'=>$this->product_id,'group_card_id'=>$lastGroupCards->id,'group_expired_at'=>Carbon::now()->addDays(cs('sale')->group_expired),'is_finished'=>0]);

			if($this->user->grade == 'vip'){
				account_group_cards($this->user)->minusGroupCards(1);
			}
			

 			//dispatch(new CloseGroupJob($this->group))->onQueue('default');
			
			//event(new OrderCreatedEvent($this->group));
			
		});

		return $this->group;
	}

	
}
